#include"LSYEasyWorld.h"
#include"Box2D\Box2D.h"
#include"GLES-Render.h"
#include"Tool.h"

b2World* LSYEasyWorld::pWorld = nullptr;
GLESDebugDraw*  LSYEasyWorld::pDebug = nullptr;
float LSYEasyWorld::PTOM = 0.03125f;
float LSYEasyWorld::delta = 0.033f;
float LSYEasyWorld::positionDelta = 10;
float LSYEasyWorld::velocityDelta = 10;

b2World * LSYEasyWorld::createWorld(const b2Vec2& gravity)
{
	if (pWorld == nullptr)
	{
		pWorld = new b2World(gravity);
	}
	return pWorld;
}

GLESDebugDraw * LSYEasyWorld::createDebug()
{
	if (pDebug == nullptr)
	{
		if (pWorld != nullptr)
		{
			pDebug = new GLESDebugDraw(1 / PTOM);
			pDebug->SetFlags(b2Draw::e_jointBit | b2Draw::e_shapeBit);
			pWorld->SetDebugDraw(pDebug);
		}
	}
	return pDebug;
}

void LSYEasyWorld::updateWorld()
{
	if (pWorld != nullptr)
		pWorld->Step(delta, velocityDelta, positionDelta);
}

float LSYEasyWorld::calcAngle(const b2Vec2& start, const b2Vec2& target)
{
	if (start.x == target.x)
	{
		return start.y < target.y ? 0 : PI;
	}
	if (start.y == target.y)
	{
		return start.x < target.x ? PI : PI * 1.5;
	}
	float dx = target.x - start.x;
	float dy = target.y - start.y;
	float angle = atanf(abs(dx / dy));
	if (start.x < target.x&&start.y < target.y)
	{
		return angle;
	}
	else if (start.x<target.x&&start.y>target.y)
	{
		return PI - angle;
	}
	else if (start.x > target.x&&start.y > target.y)
	{
		return PI + angle;
	}
	else
	{
		return 2 * PI - angle;
	}
}

b2Body * LSYEasyWorld::getBodyAt(const b2Vec2 & pos)
{
	b2Body* body = pWorld->GetBodyList();
	do
	{
		if (body->GetFixtureList()->GetShape()->TestPoint(body->GetTransform(),pos))
		{
			return body;
		}
		body = body->GetNext();
	} while (body);
	return nullptr;
}
